package ru.myrtle.umf.codegen;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;

public class Resource {

    private final File directory;
    private final String charset;

    /*
     *
     */

    public Resource(File directory, String charset) {
        this.directory = directory;
        this.charset = charset;
    }

    /*
     *
     */

    private String objectPackage;

    public String getObjectPackage() {
        return objectPackage;
    }

    public void setObjectPackage(String objectPackage) {
        this.objectPackage = objectPackage;
    }

    /*
     *
     */

    private String objectFileName;

    public String getObjectFileName() {
        return objectFileName;
    }

    public void setObjectFileName(String objectFileName) {
        this.objectFileName = objectFileName;
    }

    /*
     *
     */

    private String objectFileExtension = "java";

    public String getObjectFileExtension() {
        return objectFileExtension;
    }

    public void setObjectFileExtension(String objectFileExtension) {
        this.objectFileExtension = objectFileExtension;
    }

    /*
     *
     */

    private File getFile(boolean create) {
        File path = directory;

        if (objectPackage != null && objectPackage.length() > 0) {
            path = new File(
                    directory,
                    objectPackage.replace(
                            '.', '/'
                    )
            );
        }

        String name = objectFileName + "." + objectFileExtension;

        File file = new File(
                path, name
        );

        if (create) {
            if (!path.exists()) {
                path.mkdirs();
            }
        }

        return file;
    }

    public String getName() {
        return getFile(false).getAbsolutePath();
    }

    public boolean exists() {
        return getFile(false).exists();
    }

    public Reader getReader() throws IOException {
        return new BufferedReader(
                new InputStreamReader(
                        new FileInputStream(
                                getFile(true)
                        ),
                        charset
                )
        );
    }

    public Writer getWriter() throws IOException {
        return new BufferedWriter(
                new OutputStreamWriter(
                        new FileOutputStream(
                                getFile(true)
                        ),
                        charset
                )
        );
    }
}
